package com.airlenet.dubbo.registry.mysql;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;

import javax.sql.DataSource;
import java.sql.*;

public class MySQLRegistryFactory extends AbstractRegistryFactory {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    protected MySQLRegistry createRegistry(URL url) {
        // mysql://10.0.1.1:3306/db_s?
        if (dataSource == null) {
            if(url.getParameter("jdbcUrl") ==null){
                throw new IllegalStateException("jdbcUrl == null,please config dubbo.registries.mysql.parameters.jdbcUrl");
            }
            if(url.getParameter("jdbcUsername") ==null){
                throw new IllegalStateException("jdbcUsername == null,please config dubbo.registries.mysql.parameters.jdbcUsername");
            }
            if(url.getParameter("jdbcPassword") ==null){
                throw new IllegalStateException("jdbcPassword == null,please config dubbo.registries.mysql.parameters.jdbcPassword");
            }
            if(url.getParameter("jdbcDriverClass") ==null){
                throw new IllegalStateException("jdbcDriverClass == null,please config dubbo.registries.mysql.parameters.jdbcDriverClass");
            }
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUsername(url.getParameter("jdbcUsername"));
            druidDataSource.setPassword(url.getParameter("jdbcPassword"));
            druidDataSource.setUrl(url.getParameter("jdbcUrl"));
            druidDataSource.setDriverClassName(url.getParameter("jdbcDriverClass", "com.mysql.jdbc.Driver"));
            dataSource = druidDataSource;
        }
        MySQLRegistry mySQLRegistry = new MySQLRegistry(url, dataSource);
        mySQLRegistry.createTable();
        return mySQLRegistry;
    }
}
